package org.tagewerk.bookinfo.util;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.tagewerk.bookinfo.model.Book;

import com.google.gdata.client.books.BooksService;
import com.google.gdata.client.books.VolumeQuery;
import com.google.gdata.data.Person;
import com.google.gdata.data.books.VolumeEntry;
import com.google.gdata.data.books.VolumeFeed;
import com.google.gdata.data.dublincore.Publisher;
import com.google.gdata.data.dublincore.Title;
import com.google.gdata.util.ServiceException;

public class GoogleBookSearch {

	public static List<Book> findByQuery(String q){
		List<Book> result = new ArrayList();
		
		BooksService service = new BooksService("tagewerk-bookinfo-1");
		//myService.setUserCredentials("user@domain.com", "secretPassword");
		
		VolumeQuery query;
		try {
			query = new VolumeQuery(new URL("http://www.google.com/books/feeds/volumes"));
			// exclude no-preview books (by default, they are included)
			//query.setMinViewability(VolumeQuery.MinViewability.PARTIAL);
	
			// search for query string
			query.setFullTextQuery(q);
	
			VolumeFeed volumeFeed;
			try {
				volumeFeed = service.query(query, VolumeFeed.class);
				Book book = null;
				// print title(s) and viewability value if available
				for(VolumeEntry entry : volumeFeed.getEntries() ) {
					book = new Book();
				  for (Title t : entry.getTitles()) {
				    System.out.print(t.getValue() + "\t");
			    
				    book.setTitle(t.getValue());
				  }
				  for(Publisher p : entry.getPublishers()){
					  book.setPublisher(p.getValue());
				  }
				  for(Person a : entry.getAuthors()){
					  book.setAuthor(a.getName());
				  }
				  if(entry.getPublished()!=null)
					  book.setPublicationDate(new Date(entry.getPublished().getValue()));
				  result.add(book);
				}
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ServiceException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (MalformedURLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		return result;
	}
}
